package jp.co.jmas.jmasvideo;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jp.co.jmas.jmasvideo.dao.PMF;
import jp.co.jmas.jmasvideo.dao.UserData;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@SuppressWarnings("serial")
public class JmasvideoServlet extends HttpServlet {

	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		UserService service = UserServiceFactory.getUserService();
		String thisURL = req.getRequestURI();
		resp.setContentType("text/html");
		PrintWriter pw = resp.getWriter();

		pw.println("<!DOCTYPE html>");
		pw.println("<html><body>");

		if (req.getUserPrincipal() == null) {
			// Loginしてない
			pw.println("<a href=\"" + service.createLoginURL(thisURL) + "\">login</a>");
		} else {

			String id = req.getParameter("id");
			pw.println("<p>test movie</p>");
			pw.println("<video controls width=\"320\" height=\"240\" poster=\"" + id + ".jpg\">");
			pw.println("<source src=\"https://storage.cloud.google.com/jmas_camera/" + id + ".mp4\">");
			pw.println("</video>");

			// ユーザ情報取得
			String userName = req.getUserPrincipal().getName();
			String userAddress = null;
			String userID = null;

			PersistenceManager pm = PMF.get().getPersistenceManager();
			Query query = pm.newQuery(UserData.class);
			query.setFilter("name == '" + userName + "'");

			@SuppressWarnings("unchecked")
			List<UserData> list = (List<UserData>) query.execute();

			if (list.isEmpty()) {
				userID = "empty";
				userAddress = "empty";
			} else {
				userID = String.valueOf(list.get(0).getId());
				userAddress = list.get(0).getMail();
			}

			pw.println("<p>ID  : " + userID + "</p>");
			pw.println("<p>User: " + userName + "</p>");
			pw.println("<p>Mail: " + userAddress + "</p>");
			pw.println("<a href=\"" + service.createLogoutURL(thisURL) + "\">logout</a>");
			pw.println("</bodhy></html>");

		}

	}
}
